import { useEffect, memo, useMemo, useRef } from 'react'
import { useRequest } from 'ahooks'
import { ChargeOrder, ChargeOrderStatus, FromType, getChargeOrderDetail, getChargingHistory } from './services'
import { Badge, Card, Col, Descriptions, List, Row, Spin } from 'antd'
import { Access, styled } from '@umijs/max'
import dayjs from 'dayjs'
import { EquipmentType } from '@/pages/station/stubList/services'
import * as echarts from 'echarts'

const Container = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;

  .ant-descriptions-item-label {
    align-items: center !important;
  }
`

type OptionsParams = {
  categories: string[]
  data: {name: string, value: number[]}[]
  unit: string
}
const ChartColor = [
  ['rgba(1, 191, 236, 1)', 'rgba(1, 191, 236, 0)'],
  ['rgba(128, 255, 165, 1)', 'rgba(128, 255, 165, 0)'],
]
const getOptions = ({categories, data, unit}: OptionsParams) => {
  return {
    title: {
      text: '',
      subtext: `单位：${unit}`,
      left: 'right'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      left: 'left',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: categories,
        axisLabel: {
          formatter: (value: string) => value.substring(14),
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: data.map((item, index) => ({
      name: item.name,
      type: 'line',
      smooth: true,
      showSymbol: false,
      color: ChartColor[index][0],
      areaStyle: {
        opacity: 0.8,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: ChartColor[index][0]
          },
          {
            offset: 1,
            color: ChartColor[index][1]
          }
        ])
      },
      data: item.value
    }))
  }
}
const initChartData = (names: string[], unit: string): OptionsParams => {
  return {
    categories: [],
    data: names.map(name => ({name, value: []})),
    unit,
  }
}

const ChargeOrderDetail: React.FC<RoutePageProps> = props => {
  const voltageRef = useRef<HTMLDivElement>(null)
  const voltageLine = useRef<echarts.ECharts>()
  const currentRef = useRef<HTMLDivElement>(null)
  const currentLine = useRef<echarts.ECharts>()
  const socRef = useRef<HTMLDivElement>(null)
  const socLine = useRef<echarts.ECharts>()
  const temperatureRef = useRef<HTMLDivElement>(null)
  const temperatureLine = useRef<echarts.ECharts>()
  const powerRef = useRef<HTMLDivElement>(null)
  const powerLine = useRef<echarts.ECharts>()
  const { data: res, loading, runAsync } = useRequest(getChargeOrderDetail, {manual: true})
  const { runAsync: getChartData } = useRequest(getChargingHistory, {manual: true})

  const data = useMemo((): Partial<ChargeOrder> => {
    if (res?.data.chargeDetails) {
      res.data.chargeDetailsList = JSON.parse(res.data.chargeDetails)
    }
    return res?.data || {}
  }, [res])

  const calcValue = useMemo(() => {
    const result: any = {}
    if (!data.id) return result
    // 充电时长
    if (data.chargingTime) {
      if (data.chargingTime >= 60) {
        const hour = Math.floor(data.chargingTime / 60)
        const minute = data.chargingTime % 60
        result.chargingTime = `${hour}小时${minute ? `${minute}分钟` : ''}`
      } else {
        result.chargingTime = `${data.chargingTime}分钟`
      }
    }
    // 订单状态 & 支付状态 & 支付方式 & 充电量 & 电费 & 服务费 & 总费用
    if (data.status === ChargeOrderStatus.进行中) {
      result.status = '充电中'
      result.payStatus = '--'
      result.payMethod = '--'
      result.electric = data.power || data.electric || '--'
      result.electricFee = data.feeElectric || '--'
      result.serviceFee = data.feeService || '--'
    } else if (data.status === ChargeOrderStatus['完成充电(待支付)']) {
      if (data.feeTotal === null) {
        result.status = '结算中'
      } else if (data.paymentDeadline) {
        result.status = '自动支付中'
      } else {
        result.status = '待支付'
      }
      result.payStatus = <Badge status="error" text="待支付" />
      result.payMethod = '--'
      result.electric = data.electric || '--'
      result.electricFee = data.feeElectric || '--'
      result.serviceFee = data.feeService || '--'
    } else {
      result.status = '已支付'
      result.payStatus = <Badge status="success" text="已支付" />
      result.payMethod = data.orgName ? '企业余额' : '个人余额'
      result.electric = data.electric || '--'
      result.electricFee = data.electricFee || '--'
      result.serviceFee = data.serviceFee || '--'
    }
    return result
  }, [data])

  useEffect(() => {
    voltageLine.current = echarts.init(voltageRef.current)
    currentLine.current = echarts.init(currentRef.current)
    socLine.current = echarts.init(socRef.current)
    temperatureLine.current = echarts.init(temperatureRef.current)
    powerLine.current = echarts.init(powerRef.current)

    if (props.params.orderId) {
      runAsync({
        id: props.params.orderId,
        infoType: parseInt(props.params.infoType),
      })
      getChartData({id: props.params.orderId})
        .then(res => {
          const voltageLineData = initChartData(['桩端输出电压', '车端需求电压'], '伏')
          const currentLineData = initChartData(['桩端输出电流', '车端需求电流'], '安培')
          const socLineData = initChartData(['SOC'], '%')
          const temperatureLineData = initChartData(['枪温', '车温'], '度')
          const powerData = initChartData(['电量'], '度')

          const _data = res.data?.sort((a, b) => parseInt(a.time) - parseInt(b.time))
          _data?.forEach(item => {
            if (parseInt(item.dataType) === 1) {
              const time = dayjs(parseInt(item.time)).format('YYYY-MM-DD HH:mm:ss')

              socLineData.categories.push(time)
              socLineData.data[0].value.push(parseFloat(item.soc))
              
              temperatureLineData.categories.push(time)
              temperatureLineData.data[0].value.push(parseFloat(item.tempStub))
              temperatureLineData.data[1].value.push(parseFloat(item.tempCar))
              
              powerData.categories.push(time)
              powerData.data[0].value.push(parseFloat(item.power))
            } else if (parseInt(item.dataType) === 2) {
              const time = dayjs(parseInt(item.time)).format('YYYY-MM-DD HH:mm:ss')

              voltageLineData.categories.push(time)
              voltageLineData.data[0].value.push(parseFloat(item.voltage))
              voltageLineData.data[1].value.push(parseFloat(item.voltageCar))

              currentLineData.categories.push(time)
              currentLineData.data[0].value.push(parseFloat(item.current))
              currentLineData.data[1].value.push(parseFloat(item.currentCar))

              socLineData.categories.push(time)
              socLineData.data[0].value.push(parseFloat(item.soc))
            } else if (parseInt(item.dataType) === 3) {
              const time = dayjs(parseInt(item.time)).format('YYYY-MM-DD HH:mm:ss')

              voltageLineData.categories.push(time)
              voltageLineData.data[0].value.push(parseFloat(item.voltage))
              voltageLineData.data[1].value.push(parseFloat(item.voltageCar))

              currentLineData.categories.push(time)
              currentLineData.data[0].value.push(parseFloat(item.current))
              currentLineData.data[1].value.push(parseFloat(item.currentCar))

              socLineData.categories.push(time)
              socLineData.data[0].value.push(parseFloat(item.soc))

              powerData.categories.push(time)
              powerData.data[0].value.push(parseFloat(item.power))
            }
          })

          voltageLine.current?.setOption(getOptions(voltageLineData))
          currentLine.current?.setOption(getOptions(currentLineData))
          socLine.current?.setOption(getOptions(socLineData))
          temperatureLine.current?.setOption(getOptions(temperatureLineData))
          powerLine.current?.setOption(getOptions(powerData))
        })
    }
  }, [props.params.orderId])

  const orderInfoItems = []
  const 非互联互通启动 = !data.chargeApp || data.chargeApp === '家苑充电小程序'
  if (data.status === ChargeOrderStatus.进行中 || data.status === ChargeOrderStatus['完成充电(待支付)']) {
    orderInfoItems.push(
      {key: 'status', label: '订单状态', children: 非互联互通启动 ? calcValue.status : '无需支付'},
      {key: 'electric', label: '订单电量(度)', children: calcValue.electric},
      {key: 'electricFee', label: '订单电费(元)', children: calcValue.electricFee},
      {key: 'serviceFee', label: '订单服务费(元)', children: calcValue.serviceFee},
      {key: 'feeTotal', label: data.status === ChargeOrderStatus.进行中 ? '实时金额(元)' : '应付金额(元)', children: data.feeTotal || '--'}
    )
  } else {
    orderInfoItems.push(
      {key: 'payMethod', label: '支付方式', children: 非互联互通启动 ? calcValue.payMethod : '--'},
      {key: 'status', label: '订单状态', children: 非互联互通启动 ? calcValue.status : '无需支付'},
      {key: 'paymentTime', label: '支付时间', children: data.paymentTime ? dayjs(data.paymentTime).format('YYYY-MM-DD HH:mm:ss') : '--'},
      {key: 'electric', label: '订单电量(度)', children: calcValue.electric},
      {key: 'electricFee', label: '订单电费(元)', children: calcValue.electricFee},
      {key: 'serviceFee', label: '订单服务费(元)', children: calcValue.serviceFee},
      {key: 'totalFee', label: '订单总金额(元)', children: data.feeTotal || '--'},
      {key: 'cutMoney', label: '抵扣金额(元)', children: data.cutMoney || 0},
      {key: 'cutMoney', label: '白名单/城市会员抵扣金额(元)', children: data.freeMoney || 0},
      {key: 'cutMoney', label: '白名单/城市会员免费度数(度)', children: data.freeMoney || 0},
      {key: 'realPay', label: '实付金额(元)', children: data.realPay || '--'},
    )
  }

  return (
    <Spin spinning={loading}>
      <Container>
        <div style={{
          padding: '0 24px',
          borderRadius: 6,
          lineHeight: '36px',
          fontSize: 16,
          fontWeight: 'bold',
        }}>
          <div>{`订单号: ${props.params.orderId}`}</div>
          <Access accessible={!!data.thirdOrderId}>
            <div>{`互联互通号: ${data.thirdOrderId}`}</div>
          </Access>
        </div>
        <Card title='电站信息'>
          <Descriptions column={3}>
            <Descriptions.Item label='电站名称'>{data.stationName || '--'}</Descriptions.Item>
            <Descriptions.Item label='枪编号'>{data.stubId || '--'}</Descriptions.Item>
            <Descriptions.Item label='所在城市'>{data.cityName || '--'}</Descriptions.Item>
            <Descriptions.Item label='设备类型'>{data.stubType ? EquipmentType[data.stubType] : '--'}</Descriptions.Item>
          </Descriptions>
        </Card>
        <Access accessible={非互联互通启动}>
          <Card title='用户信息'>
            <Descriptions column={3}>
              <Descriptions.Item label='企业名称'>{data.orgName || '--'}</Descriptions.Item>
              <Descriptions.Item label='车牌号'>{data.carPlat || '--'}</Descriptions.Item>
              {/* <Descriptions.Item label='电卡卡号'>{data.stubType || '--'}</Descriptions.Item> */}
              {/* <Descriptions.Item label='Vin码'>{data.cityName || '--'}</Descriptions.Item> */}
              <Descriptions.Item label='车品牌'>{data.carBrand || '--'}</Descriptions.Item>
              <Descriptions.Item label='车型号'>{data.carSeries || '--'}</Descriptions.Item>
              <Descriptions.Item label='用户昵称'>{data.nickname || '--'}</Descriptions.Item>
              <Descriptions.Item label='手机号'>{data.telephone || '--'}</Descriptions.Item>
              {/* <Descriptions.Item label='电卡名称'>{data.stubType || '--'}</Descriptions.Item> */}
            </Descriptions>
          </Card>
        </Access>
        <Card title='充电信息'>
          <Descriptions column={3}>
            <Descriptions.Item label='启动方'>{data.chargeApp || '--'}</Descriptions.Item>
            <Descriptions.Item label='设备来源'>{data.fromType ? FromType[data.fromType] : '--'}</Descriptions.Item>
            <Descriptions.Item label='创建时间'>{data.createTime || '--'}</Descriptions.Item>
            <Descriptions.Item label='初始SOC'>{data.socBegin ? `${data.socBegin}%` : '--'}</Descriptions.Item>
            <Descriptions.Item label='结束SOC'>{data.socEnd ? `${data.socEnd}%` : '--'}</Descriptions.Item>
            <Descriptions.Item label='枪充电开始时间'>{data.beginTime || '--'}</Descriptions.Item>
            <Descriptions.Item label='枪充电结束时间'>{data.endTime || '--'}</Descriptions.Item>
            <Descriptions.Item label='充电状态'>{data.status === ChargeOrderStatus.进行中 ? '充电中' : '充电完成'}</Descriptions.Item>
            <Descriptions.Item label='停止原因'>{data.endName || '--'}</Descriptions.Item>
            <Descriptions.Item label='充电时长'>{calcValue.chargingTime || '--'}</Descriptions.Item>
          </Descriptions>
        </Card>
        <Access accessible={!!res?.data.chargeDetailsList}>
          <Card title='充电明细'>
            <Descriptions column={7} layout="vertical" bordered size='middle'>
              <Descriptions.Item label='开始时间'>
                <List
                  dataSource={res?.data.chargeDetailsList}
                  renderItem={(item: any) => <List.Item>{item[0]}</List.Item>}
                />
              </Descriptions.Item>
              <Descriptions.Item label='结束时间'>
                <List
                  dataSource={res?.data.chargeDetailsList}
                  renderItem={(item: any) => <List.Item>{item[1]}</List.Item>}
                />
              </Descriptions.Item>
              <Descriptions.Item label='电费价格'>
                <List
                  dataSource={res?.data.chargeDetailsList}
                  renderItem={(item: any) => <List.Item>{item[2]}</List.Item>}
                />
              </Descriptions.Item>
              <Descriptions.Item label='服务费价格'>
                <List
                  dataSource={res?.data.chargeDetailsList}
                  renderItem={(item: any) => <List.Item>{item[3]}</List.Item>}
                />
              </Descriptions.Item>
              <Descriptions.Item label='电费'>
                <List
                  dataSource={res?.data.chargeDetailsList}
                  renderItem={(item: any) => <List.Item>{item[4]}</List.Item>}
                />
              </Descriptions.Item>
              <Descriptions.Item label='服务费'>
                <List
                  dataSource={res?.data.chargeDetailsList}
                  renderItem={(item: any) => <List.Item>{item[5]}</List.Item>}
                />
              </Descriptions.Item>
              <Descriptions.Item label='充电量'>
                <List
                  dataSource={res?.data.chargeDetailsList}
                  renderItem={(item: any) => <List.Item>{item[6]}</List.Item>}
                />
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </Access>
        <Card title='订单详情'>
          <Descriptions
            column={3}
            items={orderInfoItems}
          />
        </Card>
        <Row gutter={[24, 24]}>
          <Col span={12}>
            <Card title='电压折线图' styles={{body: {position: 'relative'}}}>
              <div ref={voltageRef} style={{width: '100%', height: 340}}></div>
            </Card>
          </Col>
          <Col span={12}>
            <Card title='电流折线图' styles={{body: {position: 'relative'}}}>
              <div ref={currentRef} style={{width: '100%', height: 340}}></div>
            </Card>
          </Col>
          <Col span={12}>
            <Card title='SOC折线图' styles={{body: {position: 'relative'}}}>
              <div ref={socRef} style={{width: '100%', height: 340}}></div>
            </Card>
          </Col>
          <Col span={12}>
            <Card title='温度折线图' styles={{body: {position: 'relative'}}}>
              <div ref={temperatureRef} style={{width: '100%', height: 340}}></div>
            </Card>
          </Col>
          <Col span={12}>
            <Card title='电量折线图' styles={{body: {position: 'relative'}}}>
              <div ref={powerRef} style={{width: '100%', height: 340}}></div>
            </Card>
          </Col>
        </Row>
      </Container>
    </Spin>
  )
}

export default memo(ChargeOrderDetail)
